package com.ytkj.digitalConstruction.socketio;

import java.util.ArrayList;

import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;

@Component
public class App implements CommandLineRunner{
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${web.host}")
	private String host;
	
	@Value("${web.port}")
	private Integer port;
	
	public static SocketIOServer server =null;
	public static ArrayList<ClientInfo> clientInfos = new ArrayList<ClientInfo>();	
	
	@Override
	public void run(String... args) throws Exception {
		Configuration config = new Configuration();
		config.setHostname(host);
		config.setPort(port);
		try {
			//启动socket服务
			server = new SocketIOServer(config);
			
			//监听建立连接
			MyConnectListener myConnectListener = new MyConnectListener();
			server.addConnectListener(myConnectListener);
			logger.info("socketio 监听建立的连接...");
			
			//监听接收消息
			ChatListener chatListener = new ChatListener();
			App.server.addEventListener("chat",ChatObj.class, chatListener);
			
			//监听断开连接
			DisConnectListener disConnectListener = new DisConnectListener();
			server.addDisconnectListener(disConnectListener);
			
			//启动服务
			server.start();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
       /* Thread.sleep(Integer.MAX_VALUE) ;
        server.stop();*/
	}
	
	//服务关闭时回调该方法结束socket服务
	@PreDestroy
	public void destroy() {
		server.stop();
	}

}
